<template>
  <div class="upload-excel">
    <div class="btn-upload">
      <el-button
        :loading="loading"
        size="mini"
        type="primary"
        @click="handleUpload"
      >
        点击上传
      </el-button>
    </div>

    <input
      ref="excel-upload-input"
      class="excel-upload-input"
      type="file"
      accept=".xlsx, .xls"
      @change="handleClick"
    />
    <div
      class="drop"
      @drop="handleDrop"
      @dragover="handleDragover"
      @dragenter="handleDragover"
    >
      <i class="el-icon-upload" />
      <span>将文件拖到此处</span>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'
export default {
  props: {
    beforeUpload: Function, // eslint-disable-line
    onSuccess: Function // eslint-disable-line
  },
  data() {
    return {
      loading: false,
      excelData: {
        header: null,
        results: null
      }
    }
  },
  methods: {
    generateData({ header, results }) {
      this.excelData.header = header
      console.log('拿到的数据是', this.excelData)
      this.excelData.results = results

      this.onSuccess && this.onSuccess(this.excelData)
    },
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      if (this.loading) return
      const files = e.dataTransfer.files
      if (files.length !== 1) {
        this.$message.error('Only support uploading one file!')
        return
      }
      const rawFile = files[0] // only use files[0]
      if (!this.isExcel(rawFile)) {
        this.$message.error(
          'Only supports upload .xlsx, .xls, .csv suffix files'
        )
        return false
      }
      this.upload(rawFile)
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    //点击上传按钮，获得input dom元素触发input点击事件；
    handleUpload() {
      this.$refs['excel-upload-input'].click()
    },
    handleClick(e) {
      //files就是存储选择到的那个文件的变量，数据类型 数组
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      //rawFile 得到得是一个文件；
      //如果没有选择文件，就直接return 停止
      //如果有文件，那就上传该文件。
      if (!rawFile) return
      this.upload(rawFile)
    },
    upload(rawFile) {
      //清空文件框，方便用户下次上传
      this.$refs['excel-upload-input'].value = null // fix can't select the same excel
      //什么操作都不做
      if (!this.beforeUpload) {
        //调用readerData方法来读取 rawFile中的数据
        this.readerData(rawFile)
        return
      }
      //把rawFile传给beforeUpload方法做一些处理；
      const before = this.beforeUpload(rawFile)
      //如果before是有值的
      if (before) {
        //调用readerData去读取rawFile这个文件；
        this.readerData(rawFile)
      }
    },
    //无论做与不做，读取文件数据；
    readerData(rawFile) {
      //开始读取
      this.loading = true
      //返回一个promise对象
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        //reader是FileReader函数的实例对象
        //FileReader是文件读取器
        reader.onload = (e) => {
          const data = e.target.result
          //文件读取内容

          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          //一个个的styleseet的名字
          const worksheet = workbook.Sheets[firstSheetName]
          //获取一个个的工作表
          const header = this.getHeaderRow(worksheet)
          //表的表头
          const results = XLSX.utils.sheet_to_json(worksheet)
          //表的内容
          this.generateData({ header, results })
          //创建单元表格
          this.loading = false
          //读取结束
          resolve()
          //读取成功进入到promise 中的resolve函数；
        }
        reader.readAsArrayBuffer(rawFile)
      })
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    isExcel(file) {
      return /\.(xlsx|xls|csv)$/.test(file.name)
    }
  }
}
</script> 
<style scoped lang="scss">
.upload-excel {
  display: flex;
  justify-content: center;
  margin-top: 100px;
  .excel-upload-input {
    display: none;
    z-index: -9999;
  }
  .btn-upload,
  .drop {
    border: 1px dashed #bbb;
    width: 350px;
    height: 160px;
    text-align: center;
    line-height: 160px;
  }
  .drop {
    line-height: 80px;
    color: #bbb;
    i {
      font-size: 60px;
      display: block;
    }
  }
}
</style>